package org.chy.config.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author  chenghy
 * @date    2018年01月12日 15时59分29秒
 * @Description 发上等愿,结中等缘,享下等福;向高处立,就平处坐,从宽处行.
 * @Package org.chy.config.security
 */
@Configuration //扩展SpringSecurity配置需要继承此类
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 
	
	/**
	 * WebSecurityConfigurerAdapter抽象类是我们用来修改security默认配置的类.
	 */

	/*注册UserDetailsService的bean*/
	@Bean UserDetailsService customUserService() {
		return new CustomUserService();
	}
	
	/*添加自定义的UserDetailsService认证*/
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(customUserService()); 
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
			.anyRequest().authenticated() //所有请求需要认证即登录后才可访问
			.and()
			.formLogin().loginPage("/login")
			.defaultSuccessUrl("/index") //登录成功后默认跳转页面
			.failureUrl("/login?error")
			.permitAll() 				 //登录页面可任意访问
			.and()
			.rememberMe()				 //开启cookie保存用户数据
			//.tokenValiditySeconds(60 * 60 * 24 * 7) //设置cookie有效期
			//.key("")   					 //设置cookie的私钥
			.and()
			.logout()
			//.logoutUrl("/logout") 		//默认注销行为为logout,可以通过下面的方式来修改.
			//.logoutSuccessUrl("") 		//设置注销成功后跳转页面,默认是跳转到登录页面。
			.permitAll();       		//注销请求可任意访问
	}
}

















